﻿using CHSystemApi.Framework.Base;
using CHSystemApi.Framework.Extension;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace CHSystemApi.Framework.Middleware
{
    /// <summary>
    /// 异常处理中间件
    /// </summary>
    public class ExceptionMiddleware : IMiddleware
    {
        /// <summary>
        /// 请求委托
        /// </summary>
        public RequestDelegate _next { get; set; }


        public ExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// 自定义中间件处理过程
        /// </summary>
        /// <param name="httpContext">请求上下文</param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext httpContext)
        {
            //执行上下文捕获全局异常
            try
            {
                await _next(httpContext);
            }
            catch (BaseException ex)
            {
                BaseResponse response = new BaseResponse() { code = ex._code, msg = ex.Message, success = false };
                string json = JsonConvert.SerializeObject(response);
                byte[] readbytes = Encoding.UTF8.GetBytes(json);
                httpContext.Response.Headers.Add("Content-Type", "application/json");
                await httpContext.Response.Body.WriteAsync(readbytes);
            }
            catch (Exception ex)
            {
#if DEBUG
                BaseResponse response = new BaseResponse() { code = StatusCode.Internal_Server_Error, msg = ex.Message, success = false };
#else
                BaseResponse response = new BaseResponse() { code = StatusCode.Internal_Server_Error, msg = "An unexpected error has occurred!", success = false };
#endif
                string json = JsonConvert.SerializeObject(response);
                byte[] readbytes = Encoding.UTF8.GetBytes(json);
                httpContext.Response.Headers.Add("Content-Type", "application/json");
                await httpContext.Response.Body.WriteAsync(readbytes);
            }
        }
    }
}
